package com.yuji.aacar.controller.fragment.mine;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseFragment;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.base.UserCenter;
import com.yuji.aacar.bean.response.GetMyCreditResponse;
import com.yuji.aacar.bean.response.ImguploadResponse;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.bean.response.VersionResponse;
import com.yuji.aacar.controller.about.AboutActivity;
import com.yuji.aacar.controller.address.AddressActivity;
import com.yuji.aacar.controller.message.MessageActivity;
import com.yuji.aacar.controller.mine.carmanage.CarManagementActivity;
import com.yuji.aacar.controller.recharge.RechargeActivity;
import com.yuji.aacar.controller.self.SelfInfoActivity;
import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.fres.CoreImageLoader;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.tools.Tools;
import com.yuji.aacar.utils.BitmapUtils;
import com.yuji.aacar.utils.FileUtils;
import com.yuji.aacar.widgets.autolayout.AutoLinearLayout;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.dialogue.VersionDialog;
import com.yuji.aacar.widgets.popwindow.PopItemAction;
import com.yuji.aacar.widgets.popwindow.PopWindow;
import com.yuji.aacar.widgets.takephoto.app.CustomHelper;
import com.yuji.aacar.widgets.takephoto.app.TakePhoto;
import com.yuji.aacar.widgets.takephoto.app.TakePhotoImpl;
import com.yuji.aacar.widgets.takephoto.model.InvokeParam;
import com.yuji.aacar.widgets.takephoto.model.TContextWrap;
import com.yuji.aacar.widgets.takephoto.model.TResult;
import com.yuji.aacar.widgets.takephoto.permission.InvokeListener;
import com.yuji.aacar.widgets.takephoto.permission.PermissionManager;
import com.yuji.aacar.widgets.takephoto.permission.TakePhotoInvocationHandler;
import com.yuji.aacar.widgets.textview.PingFangTextView;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yuji.aacar.base.UserCenter.getCurrentUser;
import static com.yuji.aacar.service.BaseServiceMediator.GET_MY_CREDIT;

/**
 * <li>Package:com.yuji.aacar.controller.fragments.order</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/2/28</li>
 * <li>Description:   </li>
 */

public class MineFragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener {

    private static final String TAG = MineFragment.class.getName();
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.back_image)
    AutoRelativeLayout backImage;
    @BindView(R.id.title_content)
    PingFangTextView titleContent;
    @BindView(R.id.back_login)
    PingFangTextView backLogin;
    @BindView(R.id.title_message_iv)
    ImageView titleMessageIv;
    @BindView(R.id.title_message_rl)
    AutoRelativeLayout titleMessageRl;
    @BindView(R.id.title_rl)
    AutoRelativeLayout titleRl;
    @BindView(R.id.mine_header_iv)
    SimpleDraweeView mineHeaderIv;
    @BindView(R.id.mine_name)
    PingFangTextView mineName;
    @BindView(R.id.mine_rank)
    PingFangTextView mineRank;
    @BindView(R.id.mine_member_rl)
    AutoRelativeLayout mineMemberRl;
    @BindView(R.id.mine_pay_money_tv)
    PingFangTextView minePayMoneyTv;
    @BindView(R.id.mine_pay_money_ll)
    AutoLinearLayout minePayMoneyLl;
    @BindView(R.id.credit)
    TextView credit;
    @BindView(R.id.mine_one_rl)
    AutoRelativeLayout mineOneRl;
    @BindView(R.id.mine_two_rl)
    AutoRelativeLayout mineTwoRl;
    @BindView(R.id.mine_three_rl)
    AutoRelativeLayout mineThreeRl;
    @BindView(R.id.mine_four_rl)
    AutoRelativeLayout mineFourRl;
    @BindView(R.id.mine_five_rl)
    AutoRelativeLayout mineFiveRl;
    @BindView(R.id.mine_erweima)
    ImageView mineErweima;
    @BindView(R.id.mine_version)
    TextView mineVersion;


    private Activity mContext;

    private InvokeParam invokeParam;
    private TakePhoto takePhoto;
    private CustomHelper customHelper;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void showFragemt() {
        super.showFragemt();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_mine, null);
        ButterKnife.bind(this, rootView);
        titleBack.setVisibility(View.GONE);
        titleContent.setVisibility(View.GONE);
        titleMessageRl.setVisibility(View.VISIBLE);
//        titleMessageRl.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                presentControllerFromFragment(MessageActivity.class);
//                LoginResponse user = UserCenter.getCurrentUser();
//                if (null != user){
//                    UserCenter.setNewMessage(user.getMemberId(),"0");
//                    CoreEventCenter.postMessage(EventConst.PUSH_MESSAGE_CHECKED, "xiaoxi");
//                }
//            }
//        });
        mContext = getActivity();
        init(rootView);
        super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    private void init(View rootView) {
        LoginResponse user = getCurrentUser();

        if (null != user) {
            CustomHelper.AACAR_DIR = "/AaCar/" + Tools.getToken()[1] + "/temp/";
            CustomHelper.AACAR_THUMB_DIR = "/" + Tools.getToken()[1] + "/thumb/";
            customHelper = CustomHelper.of(rootView);

            CoreImageLoader.loadImage(mineHeaderIv, user.getHeadUrl());
            if (!TextUtils.isEmpty(user.getUserName())) {
                mineName.setText(user.getUserName());
            } else if (!TextUtils.isEmpty(user.getPhoneNo())) {
                mineName.setText(user.getPhoneNo());
            }

            mineRank.setText(user.getRankName());

            String version = Tools.getAppVersionName(getActivity());
            mineVersion.setText("V " + version);

            //            if (user.getRankName().contentEquals("普通会员")){
            //                mineRank.setText("普通会员");
            //                mineRank.setBackgroundResource(R.drawable.shape_grey_corners);
            //            } else if (user.getRankName().contentEquals("银牌会员")){
            //                mineRank.setText("银牌会员");
            //                mineRank.setBackgroundResource(R.drawable.shape_grey_corners);
            //            } else if (user.getRankName().contentEquals("金牌会员")){
            //                mineRank.setText("金牌会员");
            //                mineRank.setBackgroundResource(R.drawable.shape_gold_corners_btn);
            //            }
        }
    }

    @OnClick({R.id.mine_header_iv, R.id.mine_member_rl, R.id.title_message_iv, R.id.title_message_rl, R.id.title_back, R.id.mine_pay_money_tv, R.id.mine_pay_money_ll, R.id.mine_one_rl, R.id.mine_two_rl, R.id.mine_three_rl, R.id.mine_four_rl, R.id.mine_five_rl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                break;
            case R.id.mine_header_iv:
                //photo
                //                if (UserCenter.isLogin()) {
                //                    showSelectHeadPop(null);
                //                }
                showSelectHeadPop(null);
                break;
            case R.id.mine_member_rl:
                //                presentControllerFromFragment(MemberActivity.class);
                break;
            case R.id.mine_pay_money_tv:
                presentControllerFromFragment(RechargeActivity.class);
                break;
            case R.id.mine_pay_money_ll:
                presentControllerFromFragment(RechargeActivity.class);
                break;
            case R.id.mine_one_rl:
                presentControllerFromFragment(RechargeActivity.class);
                break;
            case R.id.mine_two_rl:
                presentControllerFromFragment(CarManagementActivity.class);
                break;
            case R.id.mine_three_rl:
                presentControllerFromFragment(AddressActivity.class);
                break;
            case R.id.mine_four_rl:
                presentControllerFromFragment(SelfInfoActivity.class);
                break;
            case R.id.mine_five_rl:
                presentControllerFromFragment(AboutActivity.class);
                break;
            case R.id.title_message_iv:
                toMessagePage();
                break;
            case R.id.title_message_rl:
                toMessagePage();
                break;
        }
    }

    private void toMessagePage(){
        presentControllerFromFragment(MessageActivity.class);
        LoginResponse user = UserCenter.getCurrentUser();
        if (null != user) {
            UserCenter.setNewMessage(user.getMemberId(), "0");
            CoreEventCenter.postMessage(EventConst.PUSH_MESSAGE_CHECKED, "xiaoxi");
        }
    }

    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (response.getRequestCode() == BaseServiceMediator.UPLOAD_IMAGE_CODE) {
            ImguploadResponse imguploadResponse = (ImguploadResponse) response.getResponse();
            CoreImageLoader.loadImage(mineHeaderIv, imguploadResponse.getInfo());
            LoginResponse user = getCurrentUser();
            if (null != user) {
                user.setHeadUrl(imguploadResponse.getInfo());
                UserCenter.saveCurrentUser(user);
            }
            showToast("图片上传完成！");
        } else if (response.getRequestCode() == BaseServiceMediator.GET_MY_CREDIT_CODE) {
            GetMyCreditResponse mCredit = (GetMyCreditResponse) response.getResponse();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    credit.setText(mCredit.getInteger() + "积分");
                    mineRank.setText(mCredit.getRankName());
                    LoginResponse user = UserCenter.getCurrentUser();
                    user.setRankName(mCredit.getRankName());
                    user.setRankId(mCredit.getRankId());
                    UserCenter.saveCurrentUser(user);
                }
            });
        }
    }

    @Override
    public void alreadyBindBaseViewModel() {
        super.alreadyBindBaseViewModel();
    }

    public void showSelectHeadPop(View view) {
        PopWindow popWindow = new PopWindow.Builder(mContext)
                .setStyle(PopWindow.PopWindowStyle.PopUp)
                //                .setTitle("注意")
                //                .setMessage("今天天气不错")
                .addItemAction(new PopItemAction("手机拍照", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        customHelper.onClick(CustomHelper.TAKE_PIC_TYPE_CAMERA, getTakePhoto());
                    }
                }))
                .addItemAction(new PopItemAction("从手机相册选择", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        customHelper.onClick(CustomHelper.TAKE_PIC_TYPE_ALBUM, getTakePhoto());
                    }
                }))
                //                .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                //                    @Override
                //                    public void onClick() {
                //                        Toast.makeText(mContext, "确定", Toast.LENGTH_SHORT).show();
                //                    }
                //                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .create();
        popWindow.show();
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        LogUtil.e(TAG, "takeSuccess：getCompressPath" + result.getImage().getCompressPath());
        LogUtil.e(TAG, "takeSuccess：getOriginalPath" + result.getImage().getOriginalPath());
        try {
            Bitmap bitmap = FileUtils.decodeFile(result.getImage().getCompressPath());
            LogUtil.e(TAG, "takeSuccess：bitmap" + bitmap);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    byte[] bytes = BitmapUtils.getImgByte(result.getImage().getOriginalPath());
                    if (bytes == null || bytes.length == 0) {
                        showToast("头像文件损坏或者移除！请检查");
                        return;
                    }
                    String img = new String(Base64.encodeToString(bytes, Base64.NO_WRAP));
                    requestParams = BaseServiceParams.imgupload("1", img);
                    doTask(BaseServiceMediator.IMAGE_UPLOAD);
                }
            }, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        LogUtil.e(TAG, "takeFail:" + msg);
        showToast(msg);
    }

    @Override
    public void takeCancel() {
        LogUtil.e(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onResume() {
        super.onResume();
        resetMessageStatus();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //            resetMessageStatus();
            requestCredit();
        }
    }

    private void requestCredit() {
        requestParams = BaseServiceParams.getMyCredit();
        doTask(GET_MY_CREDIT);
    }

    private void resetMessageStatus() {
        LoginResponse user = UserCenter.getCurrentUser();
        if (null != user) {
            String has = UserCenter.getNewMessage(user.getMemberId());
            if (has.contentEquals("1")) {
                titleMessageIv.setImageResource(R.mipmap.message_new_normal);
            } else {
                titleMessageIv.setImageResource(R.mipmap.message_no_normal);
            }
        }
    }

    @Override
    public void handleMessage(CoreEventBusMessage message) {
        super.handleMessage(message);
        if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PERSONAL_NICKNAME))) {
            //            String nickName = message.getMessage();
            //            mineName.setText(user.getUserName());
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PERSONAL_NAME_CHANGED))) {
            String name = message.getMessage();
            if (null != name) {
                mineName.setText(name);
            } else {
                LoginResponse user = getCurrentUser();
                if (null != user) {
                    mineName.setText(user.getPhoneNo());
                }
            }

        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.VERSION_UPDATE))) {
            if (!isHidden()) {
                VersionResponse intent = (VersionResponse) message.getMessageObjects();
                if (intent.getFlag().contentEquals("1")) {
                    VersionDialog dialog = new VersionDialog(getActivity(), intent);
                    if (!dialog.isShowing()) {
                        dialog.showDialog();
                    }
                }
            }
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PUSH_MESSAGE))) {
            if (!isHidden()) {
                titleMessageIv.setImageResource(R.mipmap.message_new_normal);
            }

        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PUSH_MESSAGE_CHECKED))) {
            if (!isHidden()) {
                titleMessageIv.setImageResource(R.mipmap.message_no_normal);
            }
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PAY_JIFEN_FINISH))) {
            requestCredit();
        }
    }
}
